package com.hsource.hsourcegateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hsource.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


/**
 * @Author itoug
 * @Crreate 2020-10-15 11:54
 */

@Component
public class AuthAndLogFilter implements GlobalFilter, Ordered {


    static final Logger logger = LogManager.getLogger("request");

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        ServerHttpResponse serverHttpResponse = exchange.getResponse();

        StringBuilder logBuilder = new StringBuilder();
        Map<String, String> params = parseRequest(exchange, logBuilder);

  ;     String uid = "";

        boolean isEcs=isExclusion(serverHttpRequest);
        if(!isEcs) {
            try {
                uid=checkToken(params, serverHttpRequest);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }

        if((!isEcs)&&StringUtils.isBlank(uid)) {
            Map map = new HashMap<>();
            map.put("code", 2);
            map.put("message", "签名验证失败");
            map.put("success", false);
            map.put("auth", null);
            map.put("data",null);
            String resp = JSON.toJSONString(map);
            logBuilder.append(",resp=").append(resp);
            logger.info(logBuilder.toString());
            DataBuffer bodyDataBuffer = serverHttpResponse.bufferFactory().wrap(resp.getBytes());
            serverHttpResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return serverHttpResponse.writeWith(Mono.just(bodyDataBuffer));
        }

        DataBufferFactory bufferFactory = serverHttpResponse.bufferFactory();
        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(serverHttpResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                    return super.writeWith(fluxBody.map(dataBuffer -> {
                        byte[] content = new byte[dataBuffer.readableByteCount()];
                        dataBuffer.read(content);
                        DataBufferUtils.release(dataBuffer);
                        String resp = new String(content, Charset.forName("UTF-8"));
                        logBuilder.append(",resp=").append(resp);
                        logger.info(logBuilder.toString());
                        byte[] uppedContent = new String(content, Charset.forName("UTF-8")).getBytes();
                        return bufferFactory.wrap(uppedContent);
                    }));
                }
                return super.writeWith(body);
            }
        };

        URI uri = exchange.getRequest().getURI();
        StringBuilder query = new StringBuilder();
        String originalQuery = uri.getRawQuery();

        if (StringUtils.isNotBlank(originalQuery)) {
            query.append(originalQuery);
            if (originalQuery.charAt(originalQuery.length() - 1) != '&') {
                query.append('&');
            }
        }

        //TODO urlencode?
        query.append("userId");
        query.append('=');
        query.append(uid);

        URI newUri = UriComponentsBuilder.fromUri(uri)
                .replaceQuery(query.toString())
                .build(true)
                .toUri();

        ServerHttpRequest request = exchange.getRequest().mutate().uri(newUri).build();

        return chain.filter(exchange.mutate().request(request).response(decoratedResponse).build());

    }

    private Map<String, String> parseRequest(ServerWebExchange exchange, StringBuilder logBuilder) {
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        String method = serverHttpRequest.getMethodValue().toUpperCase();
        logBuilder.append(method).append(",").append(serverHttpRequest.getURI());
        MultiValueMap<String, String> query = serverHttpRequest.getQueryParams();
        Map<String, String> params = new HashMap<>();
        query.forEach((k, v) -> {
            params.put(k, v.get(0));
        });
        serverHttpRequest.getHeaders().forEach((k, v) -> {
            if(k.equals("token")){
                params.put(k,v.get(0));
            }
        });
        if("POST".equals(method)) {
            String body = exchange.getAttributeOrDefault("cachedRequestBody", "");
            if(StringUtils.isNotBlank(body)) {
                logBuilder.append(",body=").append(body);
                String[] kvArray = body.split("&");
                for (String kv : kvArray) {
                    if (kv.indexOf("=") >= 0) {
                        String k = kv.split("=")[0];
                        String v = kv.split("=")[1];
                        if(!params.containsKey(k)) {
                            try {
                                params.put(k, URLDecoder.decode(v, "UTF-8"));
                            } catch (UnsupportedEncodingException e) {
                            }
                        }
                    }
                }
            }
        }
        return params;
    }

    private String checkToken(Map<String, String> params, ServerHttpRequest serverHttpRequest) throws JsonProcessingException {

        String uid="";
        String token = params.get("token");
        if(StringUtils.isBlank(token)) {
            return "";
        }
        ObjectMapper trans=new ObjectMapper();
        Claims cls = null;
        try {
            cls = JwtUtil.parseJWT(token);
        } catch (IOException e) {
            e.printStackTrace();
            return "-1";
        }

        String json2 = trans.writeValueAsString(cls);
        JSONObject jsonObject = (JSONObject) JSON.parseObject(json2);
        if(jsonObject==null){
            return "";
        }
        return jsonObject.getString("uid");
    }

    private boolean isExclusion(ServerHttpRequest serverHttpRequest){

        String url = serverHttpRequest.getPath().toString();
        String[] exclusions = {
                "/hsource-demo/user/nacos"
               ,"/hsource-user/login"
                ,"/hsource-user/sendsms"
                ,"/hsource-user/index"
                ,"/doctor-center/clinic/getClinics"
                ,"/doctor-center/citys/getCitys"
                ,"/doctor-center/callback/reply"
                ,"/doctor-center/callback/close"
                ,"/doctor-center/apkVersion/checkVersion"
                ,"/payment-center/pay/payNotify/ALIPAY"
                ,"/payment-center/pay/payNotify/WECHAT"
        };
        return Arrays.asList(exclusions).contains(url);
    }

    @Override
    public int getOrder() {
        return -20;
    }


}
